﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;

namespace TMSimulator
{
    public class FileAccessLogReader
    {
       public static List<FileAccess> getFileAccess(string logFilePath)
        {
            if (!File.Exists(logFilePath))
            {
                throw new FileNotFoundException();
            }

            StreamReader reader = new StreamReader(File.OpenRead(logFilePath));
            List<FileAccess> ans = new List<FileAccess>(); 
            
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                string[] values = line.Split(',');

                if (values.Length != 6)
                {
                    throw new Exception("Log entry not in correct format");
                }

                FileAccess newFileAccess = new FileAccess();
                
                try
                {
                    var format = "dd/MM/yyyy HH:mm:ss";
                    newFileAccess.Time = DateTime.ParseExact(values[0], format, CultureInfo.InvariantCulture);
                }
                catch (FormatException e)
                {
                    Console.Error.WriteLine("Cannot parse date, format execption. Printing stack: " + e.StackTrace);
                    continue;
                }
                catch (ArgumentNullException e)
                {
                    Console.Error.WriteLine("Cannot parse date, null exection. Printing stack: " + e.StackTrace);
                    continue;
                }

                newFileAccess.Username = values[1];

                newFileAccess.FilePath = values[2];

                newFileAccess.FileAuthor = values[3];

                try
                {
                    newFileAccess.ExposureDuration = TimeSpan.Parse(values[4]);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Cannot parse exposure duration. Printing stack: " + e.StackTrace);
                    continue;
                }

                try
                {
                    newFileAccess.FileExposurePercent = Double.Parse(values[5]);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Cannot parse exposure percentage. Printing stack: " + e.StackTrace);
                    continue;
                }

                ans.Add(newFileAccess);
            }
            
            reader.Close();
            return ans;
        }
    }
}
